<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Pay as PayMent;
use fast\Random;

class Pay extends Api{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['ali_notify', 'wx_notify'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['unifiedorder'];
    
    /**
     * 支付类型
     * @var array
     */
    private $paytype = ['alipay', 'wxpay']; 
    
    /**
     * 事件类型
     * @var array
     */
    private $eventtype = ['member', 'support'];
    
    public function _initialize(){
        parent::_initialize();
    }
    
    /**
     * 统一下单
     */
    public function unifiedorder() {
        $type = trim(strtolower($this->request->post('type')));
        $event = trim(strtolower($this->request->post('event')));
        $total = $this->request->post('total');
        
        if (! in_array($type, $this->paytype)) {
            $this->error('支付类型不对！');
        }
        
        if (! in_array($event, $this->eventtype)) {
            $this->error('事件类型不对！');
        }
        
        $title = ($event == 'member') ? '会员费' : '支持'; 
        $total = ($event == 'member') ? 366 : $total;
        
        $trade_no = date('YmdHis') . Random::numeric(6);
        $user = $this->auth->getUserinfo();
        // 保存订单数据
        $data = ['event'=>$event, 'type'=>$type, 'money'=>$total, 'trade_no'=>$trade_no, 'uid'=>$user['id'], 'phone'=>$user['mobile']];
        $res = model('order')->allowField(true)->save($data);
        // 生成订单信息
        $info = PayMent::unifiedorder($type, $title, $trade_no, $total);
        
        $this->success('Ok', $info);
    }
    
    public function ali_notify(){
        $data = $_POST;
        $trade_no = $data['out_trade_no'];
        
        $order = model('order')->where(['trade_no'=>$trade_no])->find();
        
        if ($order && $order['status'] != 1) {  // 判断订单存在，并且订单没有支付成功
            $result = PayMent::check($order['type'], $data); // 验签
            if ($result) {
                $status = $this->request->post('trade_status');
                if ($data['trade_status'] == 'TRADE_FINISHED' || $data['trade_status'] == 'TRADE_SUCCESS') {
                    $this->trade_order($order);
                    $order_status = 1;
                } else {
                    $order_status = 2;
                }
                
                // 更新订单状态
                model('order')->where(['id' => $order['id']])->update(['status'=>$order_status, 'update_time'=>time()]);
                echo "success";
                return true;
            } else {
                echo "fail";
                return false;
            }
            
        } else {
            echo "fail";
            return false;
        }
    }
    

    public function wx_notify()
    {
        $file_contents = file_get_contents('php://input');
        $data = xmltoarr($file_contents);
        $trade_no = $data['out_trade_no'];
        
        $order = model('order')->where(['trade_no'=>$trade_no])->find();
        
        if ($order && $order['status'] != 1) {  // 判断订单存在，并且订单没有支付成功
            $result = PayMent::check($order['type'], $data); // 验签
            if ($result) {
                if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS') {
                    $this->trade_order($order);
                    $order_status = 1;
                } else {
                    $order_status = 2;
                }
                
                // 更新订单状态
                model('order')->where(['id' => $order['id']])->update(['status'=>$order_status, 'update_time'=>time()]);
                echo "success";
                return true;
            } else {
                echo "fail";
                return false;
            }
            
        } else {
            echo "fail";
            return false;
        }
        
    }
    
    private function trade_order($order){
        $user = model('User')->field('id, money, is_pay')->where(['id' => $order['uid']])->find();
        $user_info = [];
        if ($user) {
            // 如果为会员缴费，更新会员信息
            if ($order['event'] == 'member') {
                $user_info['is_pay'] = 1;
            }
            $user_info['money'] = $user['money'] + $order['money'];
            $user_info['updatetime'] = time();
            model('User')->where(['id'=>$user['id']
            ])->update($user_info);
        }
    }
    
}